package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lff
 * @date 2022/2/25
 */

@WebFilter
@Slf4j

public class LoginFilter implements Filter {

    private static final AntPathMatcher ANT = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg", //放行验证码
                "/user/login",  //放行登录
                "/user/logout"  //放行退出
        };
        String url = req.getRequestURI();
        if (matchPath(urls, url)) {
            //放行指定路径的资源
            filterChain.doFilter(req, resp);
            //需要return结束拦截的方法
            return;
        }
        Long emp = (Long) req.getSession().getAttribute("emp");
        Long user = (Long) req.getSession().getAttribute("user");
        log.info("emp_id{}", emp);
        log.info("user_id{}", user);
        //不为空就放行  否则拦截，跳转登录
        if (emp != null) { //PC端
            BaseContext.setId(emp);
            filterChain.doFilter(req, resp);
            BaseContext.removeId();
            return;
        } else if (user != null) { //C端用户
            BaseContext.setId(user);
            filterChain.doFilter(req, resp);
            BaseContext.removeId();
            return;
        } else {
            resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }
    }

    /**
     * 进行路径匹配，符合条件就放行
     *
     * @param urls
     * @param url
     * @return
     */
    public boolean matchPath(String[] urls, String url) {
        for (int i = 0; i < urls.length; i++) {
            if (ANT.match(urls[i], url)) {
                return true;
            }
        }
        return false;
    }
}
